package study.datastructure.stack;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class ArrayStack<E> implements Stack<E>, Iterable<E> {
    private E[] elements; // 存储栈元素的数组
    private int size;          // 当前栈的大小
    private static final int DEFAULT_CAPACITY = 10; // 默认容量

    // 构造函数
    @SuppressWarnings("all")
    public ArrayStack() {
        elements = (E[]) new Object[DEFAULT_CAPACITY];
        size = 0;
    }
    public ArrayStack(int capacity) {
        elements = (E[]) new Object[capacity];
        size = 0;
    }

    // 入栈操作
    @Override
    public void push(E item) {
        if (isFull()) {
            throw new IllegalStateException("栈已满，无法入栈");
        }
        elements[size++] = item;
    }

    // 出栈操作
    @Override
    public E pop() {
        if (isEmpty()) {
            throw new NoSuchElementException("栈是空的，无法出栈");
        }
        E item = (E) elements[--size];
        elements[size] = null; // 释放引用
        return item;
    }

    // 查看栈顶元素
    @Override
    public E peek() {
        if (isEmpty()) {
            throw new NoSuchElementException("栈是空的，无法查看栈顶元素");
        }
        return (E) elements[size - 1];
    }

    // 判断栈是否满
    @Override
    public boolean isFull() {
        return size >= elements.length;
    }

    // 判断栈是否空
    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    // 实现 Iterable 接口
    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            private int index = 0;

            @Override
            public boolean hasNext() {
                return index < size;
            }

            @Override
            public E next() {
                if (!hasNext()) {
                    throw new NoSuchElementException();
                }
                return (E) elements[index++];
            }
        };
    }

    // 主函数用于测试
    public static void main(String[] args) {
        ArrayStack<Integer> stack = new ArrayStack<>();
        stack.push(1);
        stack.push(2);
        stack.push(3);

        System.out.println("栈顶元素: " + stack.peek()); // 输出: 3
        System.out.println("栈大小: " + stack.size);  // 输出: 3

        // 遍历栈
        for (Integer item : stack) {
            System.out.println(item);
        }

        System.out.println("出栈元素: " + stack.pop()); // 输出: 3
        System.out.println("栈是否为空: " + stack.isEmpty()); // 输出: false
        System.out.println("栈是否满: " + stack.isFull()); // 输出: false
    }
}
